/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */
package com.aroundj2me.main;

import javax.microedition.lcdui.Displayable;
import javax.microedition.rms.RecordStoreException;

import com.aroundj2me.controller.ApplicationController;
import com.aroundj2me.model.Preferences;
import com.aroundj2me.utility.AlertCreator;
import com.aroundj2me.utility.ProgressForm;

public class LoginController implements Runnable {
	private AroundJ2ME parent;
	private LoginForm loginForm;
	private RegisterForm registerForm;
	private Preferences preferences;
	
	private int type = -1; //used to identify which process is running, Register or Login
	
	private final int LOGIN_PROCESS = 0;
	private final int REGISTER_PROCESS = 1;
	private ProgressForm progress;
	
	public LoginController(AroundJ2ME parent){
		this.parent = parent;
	}
	
	/**
	 * Loads the preferences related to the user-information from
	 * the RecordStore
	 */
	public void loadPreferences() {
		try {
			preferences = new Preferences();
			loginForm.getUserField().setString(preferences.get("username"));
			loginForm.getPwdField().setString(preferences.get("password"));
		} catch (RecordStoreException e) {
			//ignore exception
		}
	}
	
	/**
	 * Stores user-related information to the RecordStore
	 * This method has to take parameters since it is also used in the loginController
	 * here after a successful registration
	 */
	public void storePreferences(String username, String password) {
		preferences.put("username", loginForm.getUserField().getString());
		preferences.put("password", loginForm.getPwdField().getString());
		try {
			preferences.save();
		} catch (RecordStoreException e) {
			//ignore exception
		}
		preferences = null;
	}
	
	/**
	 * Shows the Login-form on the display
	 *
	 */
	public void showLoginForm(){
		if(loginForm == null){
			loginForm = new LoginForm(this);
			loadPreferences();
		}
		loginForm.resetForm();
		showOnDisplay(loginForm);
	}
	
	/**
	 * Shows the Register-form on the display
	 *
	 */
	public void showRegisterForm(){
		if(registerForm == null) registerForm = new RegisterForm(this);
		registerForm.resetForm();
		showOnDisplay(registerForm);
	}
	
	/**
	 * Loads the initial Firstlife menu
	 */
	public void loadInitialFirstlifeMenu(){
		parent.doStartup();
	}
	
	/**
	 * Shows an object of type Displayable on the display
	 * @param d Displayable to show
	 */
	public void showOnDisplay(Displayable d){
		parent.getDisplay().setCurrent(d);
	}
	
	/**
	 * Does the login of the user
	 *
	 */
	public void doLogin(){
		type = LOGIN_PROCESS;
		if (!loginForm.getUserField().getString().equals("") && !loginForm.getPwdField().getString().equals("")) {
			Thread t = new Thread(this);
			t.start();
		} else {
			parent.getDisplay().setCurrent(AlertCreator.getErrorAlert("Please enter your username and password"));
		}
	}
	
	public void doLogout(){
		
	}
	
	/**
	 * Do the registration of the user
	 *
	 */
	public void doRegister() {
		type = REGISTER_PROCESS;
		String username, pass1, pass2, firstname, surname;
		username = registerForm.getUsernameField().getString();
		firstname = registerForm.getFirstnameField().getString();
		surname = registerForm.getSurnameField().getString();
		pass1 = registerForm.getPassword1Field().getString();
		pass2 = registerForm.getPassword2Field().getString();
		
		//must all contain something
		if(!username.equals("") && !pass1.equals("") && !pass2.equals("") && !firstname.equals("") && !surname.equals("")){
			//check if passwords match
			if(pass1.equals(pass2)){
				Thread t = new Thread(this);
				t.start();
			}else{
				showOnDisplay(AlertCreator.getErrorAlert("Your passwords don't match!"));
				registerForm.getPassword1Field().setString("");
				registerForm.getPassword2Field().setString("");
			}
		}else{
			showOnDisplay(AlertCreator.getErrorAlert("Not all fields have been filled out!"));
		}
	}
	
	/**
	 * Notifies the parent controller which is the main midlet that the app
	 * should destroy itself
	 */
	public void notifyDestroyed(){
		parent.notifyDestroyed();
	}

	private void hideProgressForm(int type) {
		progress.stopProgress();
		if (type == LOGIN_PROCESS) {
			parent.getDisplay().setCurrent(loginForm);
		} else {
			parent.getDisplay().setCurrent(registerForm);
		}
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {}
	}
	
	private void startProgressForm(int type) {
		progress = new ProgressForm();
		if (type == LOGIN_PROCESS) {
			progress.startProgress("Login in progress");
		} else {
			progress.startProgress("Registration in progress");
		}
		parent.getDisplay().setCurrent(progress);
	}
	
	public void run() {
		if(type == LOGIN_PROCESS){
			startProgressForm(LOGIN_PROCESS);
			try {
				String username = loginForm.getUserField().getString();
				String password = loginForm.getPwdField().getString();
				
				//TODO should be changed afterwards
				boolean success = true;
				hideProgressForm(LOGIN_PROCESS);
				if (success) {
					storePreferences(username, password);
					parent.setUsername(username);
					parent.setPassword(password);
					loadInitialFirstlifeMenu();
				} else {
					showOnDisplay(AlertCreator.getErrorAlert("Authentication failed"));
					loginForm.resetForm();
				}
			} catch (Exception e) {
				hideProgressForm(LOGIN_PROCESS);
				showOnDisplay(AlertCreator.getErrorAlert("Not possible to connect to the Internet"));
			} 
		}else if(type == REGISTER_PROCESS){
			startProgressForm(REGISTER_PROCESS);
			try {
				String username = registerForm.getUsernameField().getString();
				String password = registerForm.getPassword1Field().getString();
				
				//TODO should be changed afterwards
				boolean successRegister = true;
				hideProgressForm(REGISTER_PROCESS);
				if(successRegister){
//					do also login if register was successful
					
					//TODO should be changed afterwards
					boolean successLogin = true;
					if(successLogin){
						storePreferences(username, password);
						parent.setUsername(username);
						parent.setPassword(password);
						loadInitialFirstlifeMenu();
					}else{
						showLoginForm();
					}
					//TODO Show a message and then redirect to main firstlife menu
					//controller.getDisplay().setCurrent(AlertCreator.getInfoAlert(contactList.getOperationDetails()));
				}else{
					
					//TODO should be changed afterwards
					showOnDisplay(AlertCreator.getErrorAlert("Error"));
				}
			} catch (Exception e) {
				hideProgressForm(REGISTER_PROCESS);
				showOnDisplay(AlertCreator.getErrorAlert("Not possible to connect to the Internet"));
			}
		}
	}
}
